import { ref, unref, reactive, nextTick, computed } from 'vue';
import { ChangeEvent } from 'ant-design-vue/lib/_util/EventInterface';
import { INode, ILink, NodesType } from '../../type/index';
import { CommonNodeTypeEnum, ActiveTypeEnum } from '../../type/enums';

// 导出逻辑函数
export const useFlowAttr = (props: any, emit: any) => {
  const formItemLayout = reactive({
    labelCol: { span: 16 },
    wrapperCol: { span: 16 },
  });

  function handleColorPicker() {
    const myEvent = new Event('resize');
    window.dispatchEvent(myEvent);
  }

  // 深拷贝函数
  function deepClone(obj: any) {
    if (obj === null || typeof obj !== 'object') {
      return obj;
    }
    
    if (Array.isArray(obj)) {
      return obj.map(item => deepClone(item));
    }
    
    const result: any = {};
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        result[key] = deepClone(obj[key]);
      }
    }
    return result;
  }

  // 标志位，防止递归触发
  let isUpdating = false;

  // 使用深拷贝创建当前选中对象
  const currentSelect = ref<INode | ILink>(deepClone(props.select));
  
  // 本地存储文本列表
  const localTextList = ref<Array<{name: string, time: string}>>([]);
  
  // 计算属性：判断当前节点是否支持文本列表
  const hasTextList = computed(() => {
    return currentSelect.value && 
          'textList' in currentSelect.value && 
          currentSelect.value.type !== 'link';
  });
  
  // 初始化本地文本列表
  function initLocalTextList() {
    if (hasTextList.value) {
      const textList = (currentSelect.value as INode).textList || [];
      localTextList.value = textList.map(item => ({
        name: item.name || '',
        time: item.time || ''
      }));
    } else {
      localTextList.value = [];
    }
  }

  const activeKey = ref<string>(ActiveTypeEnum.CANVAS);

  // 更新文本项名称
  function updateTextItemName(index: number, value: string) {
    if (index >= 0 && index < localTextList.value.length) {
      localTextList.value[index].name = value;
      syncTextListChanges();
    }
  }
  
  // 更新文本项时间
  function updateTextItemTime(index: number, value: string) {
    if (index >= 0 && index < localTextList.value.length) {
      localTextList.value[index].time = value;
      syncTextListChanges();
    }
  }

  // 同步文本列表变更到当前选中节点，避免递归更新
  function syncTextListChanges() {
    if (isUpdating || !hasTextList.value) return;
    
    isUpdating = true;
    nextTick(() => {
      const newTextList = localTextList.value.map(item => ({
        name: item.name,
        time: item.time
      }));
      
      // 直接修改原始节点数据
      const nodeId = currentSelect.value.id;
      const originalNode = props.flowData.nodeList.find((n: INode) => n.id === nodeId);
      if (originalNode) {
        originalNode.textList = newTextList;
        
        // 更新当前选择对象，但不触发监听
        (currentSelect.value as INode).textList = newTextList;
        
        // 通知父组件
        emit('update:select', currentSelect.value);
      }
      
      isUpdating = false;
    });
  }

  // 修改节点名称
  function nodeNameChange(e: ChangeEvent) {
    if (isUpdating) return;
    
    if (currentSelect.value && 'nodeName' in currentSelect.value) {
      const newName = e.target.value ?? '';
      
      isUpdating = true;
      nextTick(() => {
        // 更新当前节点名称
        (currentSelect.value as INode).nodeName = newName;
        
        // 更新原始节点
        const nodeId = currentSelect.value.id;
        const originalNode = props.flowData.nodeList.find((n: INode) => n.id === nodeId);
        if (originalNode) {
          originalNode.nodeName = newName;
          
          // 通知父组件
          emit('update:select', currentSelect.value);
        }
        
        isUpdating = false;
      });
    }
  }

  // 修改节点图标
  function nodeIconChange(e: ChangeEvent) {
    if (isUpdating) return;
    
    if (currentSelect.value && 'icon' in currentSelect.value) {
      const newName = e.target.value ?? '';
      
      isUpdating = true;
      nextTick(() => {
        // 更新当前节点名称
        (currentSelect.value as INode).icon = newName;
        
        // 更新原始节点
        const nodeId = currentSelect.value.id;
        const originalNode = props.flowData.nodeList.find((n: INode) => n.id === nodeId);
        if (originalNode) {
          originalNode.icon = newName;
          
          // 通知父组件
          emit('update:select', currentSelect.value);
        }
        
        isUpdating = false;
      });
    }
  }

  // 修改节点颜色
  function nodeColorChange(newColor: string, type: 'bgColor' | 'fontColor') {
    if (isUpdating) return;
      
    if (currentSelect.value && type in currentSelect.value) {
      isUpdating = true;
      nextTick(() => {
        // 直接使用传入的颜色值
        (currentSelect.value as INode)[type] = newColor;
        
        // 更新原始节点
        const nodeId = currentSelect.value.id;
        const originalNode = props.flowData.nodeList.find((n: INode) => n.id === nodeId);
        if (originalNode) {
          originalNode[type] = newColor;
          
          // 通知父组件
          emit('update:select', currentSelect.value);
        }
        
        isUpdating = false;
      });
    }
  }

  // 是否可以修改节点名称
  function isAllowChange(type: NodesType) {
    return ![
      CommonNodeTypeEnum.START,
      CommonNodeTypeEnum.END,
      CommonNodeTypeEnum.GATEWAY,
      CommonNodeTypeEnum.EVENT,
    ].includes(type as CommonNodeTypeEnum);
  }

  // 修改连接文本
  function linkLabelChange(e: ChangeEvent) {
    if (isUpdating) return;
    
    let label = e.target.value ?? '';
    if (currentSelect.value && 'sourceId' in currentSelect.value) {
      isUpdating = true;
      nextTick(() => {
        (currentSelect.value as ILink).label = label;
        
        // 更新原始连线
        const linkId = currentSelect.value.id;
        const originalLink = props.flowData.linkList.find((l: ILink) => l.id === linkId);
        if (originalLink) {
          originalLink.label = label;
        }
        
        // 更新UI连线标签
        let conn = props.plumb.getConnections({
          source: (unref(currentSelect) as ILink).sourceId,
          target: (unref(currentSelect) as ILink).targetId,
        })[0];
        
        if (conn) {
          let link_id = conn.canvas.id;
          let labelHandle = (e: Event) => {
            e.stopPropagation();
            const linkItem = props.flowData.linkList.find((l: ILink) => l.id === link_id);
            if (linkItem) {
              currentSelect.value = deepClone(linkItem);
              initLocalTextList();
            }
          };

          if (label !== '') {
            conn.setLabel({
              label: label,
              cssClass: `linkLabel ${link_id}`,
            });
            // 添加label点击事件
            const labelElement = document.querySelector('.' + link_id);
            if (labelElement) {
              // 移除旧的事件监听器，避免重复添加
              labelElement.removeEventListener('click', labelHandle);
              labelElement.addEventListener('click', labelHandle);
            }
          } else {
            // 移除label点击事件
            const labelElement = document.querySelector('.' + link_id);
            if (labelElement) {
              labelElement.removeEventListener('click', labelHandle);
            }

            let labelOverlay = conn.getLabelOverlay();
            if (labelOverlay) conn.removeOverlay(labelOverlay.id);
          }
        }
        
        // 通知父组件
        emit('update:select', currentSelect.value);
        
        isUpdating = false;
      });
    }
  }

  // 添加文本项
  function addTextItem() {
    if (isUpdating || !hasTextList.value) return;
    
    localTextList.value.push({
      name: '',
      time: new Date().toISOString().split('T')[0], // 默认当前日期
    });
    
    syncTextListChanges();
  }

  // 删除文本项
  function removeTextItem(index: number) {
    if (isUpdating || !hasTextList.value) return;
    
    if (index >= 0 && index < localTextList.value.length) {
      localTextList.value.splice(index, 1);
      syncTextListChanges();
    }
  }

  // 监听选中对象的变化
  watch(
    () => props.select,
    (val) => {
      if (isUpdating) return;
      
      isUpdating = true;
      nextTick(() => {
        // 使用深拷贝避免引用问题
        currentSelect.value = deepClone(val);
        
        // 初始化本地文本列表
        initLocalTextList();
        
        // 设置活动标签页
        if (!unref(currentSelect)?.type) {
          activeKey.value = ActiveTypeEnum.CANVAS;
        } else if (unref(currentSelect)?.type === 'link') {
          activeKey.value = ActiveTypeEnum.CONNECTION;
        } else {
          activeKey.value = ActiveTypeEnum.NODE;
        }
        
        isUpdating = false;
      });
    },
    { deep: true, immediate: true }
  );

  return {
    formItemLayout,
    currentSelect,
    localTextList,
    hasTextList,
    activeKey,
    ActiveTypeEnum,
    handleColorPicker,
    updateTextItemName,
    updateTextItemTime,
    nodeNameChange,
    nodeIconChange,
    nodeColorChange,
    isAllowChange,
    linkLabelChange,
    addTextItem,
    removeTextItem
  };
};